import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import axios from '../utils/axios';
import { useAuth } from './AuthContext';

const ResourceContext = createContext();

export function ResourceProvider({ children }) {
  const { token, isAuthenticated } = useAuth();
  const [resources, setResources] = useState([]);
  const [userActivities, setUserActivities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 获取所有资源
  const fetchResources = useCallback(async () => {
    try {
      setLoading(true);
      const response = await axios.get('/api/resources');
      setResources(response.data);
      setError(null);
    } catch (err) {
      console.error('获取资源失败:', err);
      setError('获取资源失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 获取用户参与的活动
  const fetchUserActivities = useCallback(async () => {
    if (!isAuthenticated || !token) return;
    
    try {
      setLoading(true);
      console.log('获取用户活动...');
      const response = await axios.get('/api/resources/user/activities');
      console.log('用户活动响应:', response.data);
      setUserActivities(response.data);
      setError(null);
    } catch (err) {
      console.error('获取用户活动失败:', err);
      setError('获取用户活动失败');
    } finally {
      setLoading(false);
    }
  }, [isAuthenticated, token]);

  // 参与活动
  const joinActivity = useCallback(async (activityId) => {
    if (!isAuthenticated || !token) return false;
    
    try {
      setLoading(true);
      await axios.post(`/api/resources/${activityId}/join`, {}, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      // 重新获取用户活动
      await fetchUserActivities();
      return true;
    } catch (err) {
      console.error('参与活动失败:', err);
      setError(err.response?.data?.message || '参与活动失败');
      return false;
    } finally {
      setLoading(false);
    }
  }, [isAuthenticated, token, fetchUserActivities]);

  // 初始加载
  useEffect(() => {
    fetchResources();
    if (isAuthenticated) {
      fetchUserActivities();
    }
  }, [fetchResources, fetchUserActivities, isAuthenticated]);

  const value = {
    resources,
    userActivities,
    loading,
    error,
    fetchResources,
    fetchUserActivities,
    joinActivity
  };

  return (
    <ResourceContext.Provider value={value}>
      {children}
    </ResourceContext.Provider>
  );
}

export function useResources() {
  return useContext(ResourceContext);
} 